package com.neteast.video.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.neteast.video.GlobalConstant;
import com.neteast.video.callback.DownloadListener;

import android.os.AsyncTask;
/**
 * 该类实现异步从服务器端下载视频文件
 * @author emellend
 *
 */
public class AsyncDownLoadManager extends AsyncTask<String, Object, File>{
	private DownloadListener mListener;
	public AsyncDownLoadManager(DownloadListener listener) {
		mListener=listener;
	}
	@Override
	protected File doInBackground(String... params) {
		final String url=params[0];
		final String saveFilePath=params[1];
		File saveFile=downLoadFile(url,saveFilePath);
		return saveFile;
	}
	/**
	 * 从服务器下载文件到本地的方法
	 * @param path  
	 * @param saveFilePath
	 * @return
	 */
	private File downLoadFile(String path, String saveFilePath) {
		try {
			URL url=new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5*1000);
			int remoteFileSize = conn.getContentLength();
			if (conn.getResponseCode()==200&&remoteFileSize>0) {
				publishProgress(GlobalConstant.FILE_DOWNLOAD_CONNECT);
				InputStream inputStream = conn.getInputStream();
				return copyStreamData2File(inputStream,saveFilePath,remoteFileSize);
			}else {
				publishProgress(GlobalConstant.FILE_DOWNLOAD_ERROR,new Exception("连接服务器失败"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			publishProgress(GlobalConstant.FILE_DOWNLOAD_ERROR,e);
		}
		return null;
	}
	/**
	 * 	从输入流中读取数据存储到文件，并实时更新文件下载进度的方法
	 * @param in 从服务器端获取的文件输入流
	 * @param saveFilePath	要存储文件的地址字符串
	 * @param remoteFileSize	服务器端文件的大小
	 * @return	下载完成后的本地文件
	 * @throws Exception
	 */
	private File copyStreamData2File(InputStream in,String saveFilePath,int remoteFileSize) throws Exception {
		byte[] buffer=new byte[1024];
		int len=0;
		int hasDown=0;
		File file=new File(saveFilePath);
		OutputStream out=new FileOutputStream(file);
		while ((len=in.read(buffer))>0) {
			out.write(buffer, 0, len);
			hasDown+=len;
			int percent=hasDown/remoteFileSize;
			publishProgress(GlobalConstant.FILE_DOWNLOAD_UPDATE,percent);
		}
		in.close();
		out.close();
		publishProgress(GlobalConstant.FILE_DOWNLOAD_COMPLETE,file);
		return file;
	}

	@Override
	protected void onProgressUpdate(Object... values) {
		int type=(Integer) values[0];
		switch (type) {
		case GlobalConstant.FILE_DOWNLOAD_CONNECT:
			mListener.onDownloadConnect(this);
			break;
		case GlobalConstant.FILE_DOWNLOAD_UPDATE:
			mListener.onDownloadUpdate(this, (Integer)values[1]);
			break;
		case GlobalConstant.FILE_DOWNLOAD_COMPLETE:
			mListener.onDownloadComplete(this, (File)values[1]);
			break;
		case GlobalConstant.FILE_DOWNLOAD_ERROR:
			mListener.onDownloadError(this, (Exception)values[1]);
			break;
		}
		super.onProgressUpdate(values);
	}
	
}
